﻿using System;
using System.Globalization;
using System.Web.Security;
using Pantry.Commons;
using Pantry.Business;
using Pantry.Entity;
using System.Web;

namespace Pantry.Web.Users
{
    public partial class LogOn : System.Web.UI.Page
    {
        private AccountBus _accountBus;
        private User _user;
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                HttpCookie httpCookie = Request.Cookies["CookieLogOn"];
                if (httpCookie != null)
                {
                    Session["user"] = httpCookie["username"];
                    Session["role"] = httpCookie["role"];
                    Response.Redirect(Request.QueryString["ReturnUrl"] ?? "~/Users/Default.aspx");
                }
                SetFocus(TextBoxUserName);
            }
        }

        protected void ButtonLogOnClick(object sender, EventArgs e)
        {
            try
            {
                _accountBus = new AccountBus();
                _user = new User
                            {
                                UserName = TextBoxUserName.Text,
                                Password = CryptographyHelper.EncryptionMD5(TextboxPassword.Text)
                            };
                if (_accountBus.LogOn(_user))
                {
                    if(CheckboxRemember.Checked)
                    {
                        var httpCookie = new HttpCookie("CookieLogOn");
                        httpCookie["username"] = TextBoxUserName.Text;
                        httpCookie["role"] = _accountBus.GetRole(_user).ToString();
                        httpCookie.Expires = DateTime.Now.AddDays(7);
                        Response.Cookies.Add(httpCookie);
                        Request.Cookies.Add(httpCookie);
                    }
                    Session["user"] = _user.UserName;
                    Session["role"] = _accountBus.GetRole(_user);
                    Response.Redirect(Request.QueryString["ReturnUrl"] ?? "~/Users/Default.aspx");
                }
                else
                {
                    LabelErrorLogOn.Text = "UserName Or Password Invalid";
                }
            }
            catch (Exception ex)
            {
                LabelErrorLogOn.Text = ex.Message;
            }
        }
    }
}
